<template>
  <div class="setting-container">
    <el-card v-loading="loading">
      <!-- tab标签栏 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="角色管理" name="role">
          <el-button
            type="primary"
            size="medium"
            style="margin: 15px 0px;"
            @click="showDialog = true"
          >+ 新增角色</el-button>
          <el-table
            :data="list"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              :index="indexFn"
              align="center"
            />
            <el-table-column
              prop="name"
              label="角色名"
              width="200"
              align="center"
            />
            <el-table-column
              prop="description"
              label="描述"
              width="400"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button type="text" @click="showAssign(row)">分配权限</el-button>
                <el-button type="text" @click="showFn(row)">修改</el-button>
                <el-button type="text" @click="delFn(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row type="flex" justify="end" style="margin-top: 20px">
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              :page-size="pagesize"
              :current-page="page"
              @current-change="currentChange"
            />
          </el-row>
          <!-- 修改dialog弹窗 -->
          <el-dialog
            :title="showTitle"
            :visible="showDialog"
            width="50%"
            @close="closeFn"
          >
            <el-form ref="form" :model="form" label-width="80px" :rules="rules">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入角色名" />
              </el-form-item>
              <el-form-item label="角色描述" prop="description">
                <el-input v-model="form.description" placeholder="请对该角色进行描述" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="showDialog = false">取 消</el-button>
              <el-button type="primary" @click="addRole">确 定</el-button>
            </template>
          </el-dialog>
          <!-- 分配权限dialog弹窗 -->
          <el-dialog title="分配权限" :visible.sync="showAssignDialog">
            <el-tree
              ref="tree"
              v-loading="assignLoading"
              node-key="id"
              :data="permissionList"
              :props="defaultProps"
              show-checkbox
              check-strictly
              default-expand-all
            />
            <template #footer>
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="assign">确定</el-button>
            </template>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="company">
          <el-alert
            title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            show-icon
            @closable="false"
          />
          <el-form style="margin: 30px 100px 0; " label-width="120px">
            <el-form-item label="企业名称">
              <el-input v-model="companyform.name" disabled style="width: 400px" />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="companyform.companyAddress" disabled style="width: 400px" />
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input v-model="companyform.companyPhone" disabled style="width: 400px" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="companyform.mailbox" disabled style="width: 400px" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="companyform.remarks" disabled style="width: 400px" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

    </el-card>
  </div>
</template>

<script>
import {
  getRoleList,
  delRole,
  addRole,
  getRoleDetail,
  updateRole,
  getCompanyDetail,
  assignRole
} from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { mapState } from 'vuex'
import { ListToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',
      list: [],
      pagesize: 5,
      page: 1,
      total: 0,
      loading: false,
      // 控制修改弹窗显示和隐藏
      showDialog: false,
      // 控制分配权限弹窗的显示和隐藏
      showAssignDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      companyform: {},
      permissionList: [],
      defaultProps: {
        label: 'name'
      },
      roleId: '',
      assignLoading: false
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    },
    ...mapState('user', ['userInfo'])
  },
  created() {
    this.getRoleList()
    this.getCompany()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const data = await getRoleList(this.page, this.pagesize)
      this.list = data.rows
      this.total = data.total
      this.loading = false
    },
    currentChange(value) {
      this.page = value
      this.getRoleList()
    },
    indexFn(index) {
      return (index + 1) + this.pagesize * (this.page - 1)
    },
    // 删除角色
    async delFn(id) {
      try {
        await this.$confirm('你确定要删除该角色吗？', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      await delRole(id)
      this.$message.success('删除成功')
      // 重新渲染
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.getRoleList()
    },
    closeFn() {
      this.showDialog = false
      this.form = {
        name: '',
        region: ''
      }
      this.$refs.form.resetFields()
    },
    // 添加角色/编辑角色
    async addRole() {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        await updateRole(this.form)
      } else {
        await addRole(this.form)
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
      }
      this.$message.success('添加角色成功')
      // 关闭弹窗
      this.closeFn()
      // 重新渲染
      this.getRoleList()
    },
    // 控制修改弹窗
    async showFn(row) {
      this.showDialog = true
      const data = await getRoleDetail(row.id)
      // console.log(data)
      this.form = data
    },
    // 获取和渲染公司信息
    async getCompany() {
      const data = await getCompanyDetail(this.userInfo.companyId)
      this.companyform = data
    },
    // 控制分配权限的弹窗
    async showAssign(row) {
      // 弹窗显示
      this.showAssignDialog = true
      // 加loading效果
      this.assignLoading = true
      // 发送请求拿到所有权限列表
      const data = await getPermissionList()
      // 请求回来的数据转树状并存在data中
      this.permissionList = ListToTree(data, '0')
      // 发送请求获取到当前角色的权限
      const { permIds } = await getRoleDetail(row.id)
      // 组件封装好的方法回显该角色已有的权限
      this.$refs.tree.setCheckedKeys(permIds)
      // 点击确定修改时需要用到当前角色id所以存到data中
      this.roleId = row.id
      this.assignLoading = false
    },
    // 关闭分配权限的dialog弹窗
    cancel() {
      this.showAssignDialog = false
    },
    // 点击分配权限的确定发送请求分配权限
    async assign() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignRole(this.roleId, permIds)
      this.$message.success('修改权限成功')
      this.showAssignDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.setting {
  &-container {
    margin: 30px;
  }
}
</style>
